// pages/card/card.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        StatusBar: app.globalData.StatusBar,
        CustomBar: app.globalData.CustomBar,
        carInfo:{
        },
        secondBatchInfo:{
            secondBatchId:''
        },
        dealerInfo:{},
        userInfo:{},
        seeImages: false,
        imageList:[],
        imageIndex:0,
        modalName:  null,
        userAgreement: true,
        secondBatchTimer: null,
        orderInfo:{
            orderNo:'',
            payInfo:{}
        },
        labelApplyList:['诚心想要','等你还价','先看再买','在线等回'],
        nowCurrent:0,
        reporType:{
          'c300InsuranceReport':'车300碰撞保险记录',
          'c300MtnceReport':'车300保养维修记录',
          'cbsInsuranceReport':'查博士碰撞保险记录',
          'cbsMtnceReport':'查博士保养维修记录'
        },
        applyReportType:'',
    },

        // 分享车辆
        openShare(){
            this.showShareModal();
        },
        showShareModal(){
            // 请求小程序二维码
            app.sHttp.shareqrCode({pageUrl:'pages/card/secondBatch/secondBatch',scene:'sid='+this.data.secondBatchInfo.secondBatchId+'&bsid='+this.data.userInfo.userId}).then(res =>{
                this.selectComponent('#posterComponent').showShareModal(res.base64);
            },err=>{
                app.error(err.msg);
            });
            },

        
        // 下载车辆素材
        downLoadCarImg(e){
        let index = 0;
        this.data.seeImages?index = this.data.imageIndex : index = this.data.nowCurrent;
        // let imagePath = this.data.carInfo.carPicList[index].picUrl;
        let self = this;
        wx.showModal({
          title: '提示',
          content: '您确定下载当前图片包吗？共' + self.data.carInfo.carPicList.length +'张图片。',
          success (res) {
            if (res.confirm) {
              let imageList = self.data.carInfo.carPicList;
              wx.showLoading({
                title: '下载素材中',
                mask: true //默认蒙层。防止触摸穿透
              });
              imageList.forEach((item,index) =>{
                self.downLoadNetImage(item.picUrl,index,self.data.carInfo.carPicList.length);
              })
            }
          }
        })
        },
        downLoadNetImage(path,index,allLong){
            wx.showLoading({
                title: '下载素材中',
                mask: true //默认蒙层。防止触摸穿透
            })
            wx.downloadFile({
            url: path,
            success: function (res) {
                wx.saveImageToPhotosAlbum({
                filePath: res.tempFilePath,
                success () {
                    if(index+1 >= allLong){
                      wx.hideLoading()
                      app.alert("全部素材已保存到您的手机")
                      wx.hideLoading();
                    }
                },
                fail () {
                    wx.hideLoading()
                    app.alert("保存失败")
                }
                })
            }
            })
        },
      carImageChange(e){
        this.setData({
          'nowCurrent': e.detail.current
        })
      },
    /**
     * 生命周期函数--监听页面加载
     */
    doNothing(){},
    onLoad: function (options) {
        // 必须一个一口价的ID
        let sid = null;
        if(undefined != options.sid){
            sid = options.sid;
        }else if(options.scene){
          let scanData = decodeURIComponent(options.scene);
          sid = app.GetQueryString(scanData,'sid');
          var value = wx.getStorageSync('user_bsid');
          if(value != undefined && value != 'undefined' && value != null && value != 'null' && value != ''){ 
            app.globalData.shareUserId = value;
          }else{
            if(app.GetQueryString(scanData,'bsid')){
              wx.setStorageSync('user_bsid', app.GetQueryString(scanData,'bsid'));
              app.globalData.shareUserId = app.GetQueryString(scanData,'bsid');
            }else{
                // 当前小程序码已过期，请重新生成海报
              wx.showModal({
                title: '海报过期提醒',
                content: '当前小程序码已过期，请重新生成海报',
                confirmText: '我知道啦',
                showCancel: false,
                success(res) {
                }
              })
            }
          }
        }
        if(sid){
          let self = this;
          this.setData({
            'secondBatchInfo.secondBatchId': sid
          },()=>{
              self.InitUserStatus();
          })
        }else{
          app.showNoAuthOrNoGrant('未找到您要查看的一口价信息');
        }
    },
    copyRecommendReasons(){
      let recommendReasons = this.data.carInfo.recommendReasons;
      wx.setClipboardData({
        data: recommendReasons,
        success: function (res) {
          wx.getClipboardData({
            success: function (res) {
              wx.showToast({
                title: '已为您复制推荐理由',
                icon:'none'
              })
            }
          })
        }
      })
  },
    // 支付定金弹窗
    goPayDepositAmount(){
        if (2 != this.data.userInfo.accountStatus) {
            app.alert('您当前尚未注册，无法支付定金');
            return;
        }
        if (1 == this.data.secondBatchInfo.isPayDepositAmount) {
            app.alert('定金已支付');
            return;
        }
        this.setData({
            'modalName': 'bargain'
        })
    },
    toDoPay(){
        let secondBatchId = this.data.secondBatchInfo.secondBatchId;
        if (null == secondBatchId || undefined == secondBatchId || '' == secondBatchId) {
            app.error('未知一口价信息');
            return;
        }
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
            app.sHttp.secondBatchOrderCreate(secondBatchId).then(res =>{
                let self = this;
                this.setData({
                    'orderInfo.orderNo': res.result.orderNo,
                    'orderInfo.payInfo': res.result.payInfo
                }, () => {
                    self.tuneUpPay();
                });
            },err=>{
              app.error(err.msg);
            })
        }else{
            this.tuneUpPay();
        }
    },    
    tuneUpPay(){
        // 从Data里面拿参数
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo || undefined == orderInfo.payInfo.paySign) {
            app.alert('支付参数不完整');
            return;
        };
        // 吊起支付。
        let self = this;
        wx.requestPayment({
            timeStamp: orderInfo.payInfo.timeStamp,
            nonceStr: orderInfo.payInfo.nonceStr,
            package: orderInfo.payInfo.package,
            signType: orderInfo.payInfo.signType,
            paySign: orderInfo.payInfo.paySign,
            success (res) {
                // 查询订单完成信息。
                let _this = self;
                app.showLoading('查询订单状态');
                setTimeout(() => {
                    wx.hideLoading();
                    _this.secondBatchOrderPayResult();
                }, 5000);
            },
            fail (res) {
                app.alert('您已取消支付，可点击立即支付重新支付');
            }
          })
    },    
    secondBatchOrderPayResult(){
        let orderInfo = this.data.orderInfo;
        if ('' == orderInfo.orderNo) {
            app.alert('支付参数不完整');
            return;
        };
        app.sHttp.secondBatchOrderPayResult(orderInfo.orderNo).then(res =>{
            let orderStatus = res.orderStatus;
            if (0 == orderStatus) {
                this.wxShowModal('查询结果','请等待几分钟后重新进入查看是否支付成功，如长时间未显示未支付成功状态，请联系客服处理');
                return;
            }
            if (1 == orderStatus) {
                this.wxShowModal('支付成功','您已支付成功');
                return;
            }
        },err=>{
          app.error(err.msg);
        })
    },    
    wxShowModal(title,content){
        let self = this;
        wx.showModal({
            title: title,
            content: content,
            confirmText: '我知道了',
            showCancel: false,
            success(res) {
                self.hideModal();
                self.setData({
                    'secondBatchInfo.isPayDepositAmount': 1
                })
            }
          })
    },
    makePhoneCall(){
        if (2 != this.data.userInfo.accountStatus) {
            app.alert('您当前尚未注册，无法拨打电话');
            return;
        }
        let contactMobile = this.data.dealerInfo.contactMobile;
        if (undefined != contactMobile && null != contactMobile && '' != contactMobile) {
            wx.makePhoneCall({
                phoneNumber: contactMobile,
                success:function(){},
                fail:function(){}
            })
        }else{
            app.alert('未查询到车主电话');
        }
    },
    // 检查一下登录状态。
    async InitUserStatus(){
        app.showLoading("获取用户信息");
        await app.checkToken();
        this.InitUserInfo();
        wx.hideLoading();
    },
    InitUserInfo(){
        this.setData({
            'userInfo': app.globalData.userInfo
        });
        app.sHttp.secondBatchView(this.data.secondBatchInfo.secondBatchId).then(res=>{
            let imageList = [];
            res.result.carInfo.carPicList.forEach(item =>{
                imageList.push(item.picUrl);
            })
            if(res.result.carInfo.insuranceReportType || res.result.carInfo.mtnceReportType){
              res.result.carInfo.haveReport = true;
            }else{
              res.result.carInfo.haveReport = false;
            }
            // 处理两个时间，
            res.result.carInfo.licensingTime = this.handleTimesForRI(res.result.carInfo.licensingTime || '');
            res.result.carInfo.compulsoryInsuranceTime = this.handleTimesForRI(res.result.carInfo.compulsoryInsuranceTime);
            res.result.carInfo.yearlyInspectionTime = this.handleTimesForRI(res.result.carInfo.yearlyInspectionTime);
            this.setData({
                'imageList': imageList,
                'carInfo': res.result.carInfo,
                'dealerInfo': res.result.dealerInfo,
                'secondBatchInfo':res.result.secondBatchInfo
            });
            // this.handleTimer();
        },err=>{
            app.error(err.msg);
            let self = this;
            setTimeout(() => {
                self.BackPage();
            }, 1500);
        })
    },
    // 计算倒计时。
    handleTimer(){
         var that = this
        //  var pingData = [that.data.secondBatchInfo];
        //  for (var i = 0; i < pingData.length;i++){
        //      var endtime = pingData[i].secondBatchTime;
        //      pingData[i].time = that.queryTime(endtime)
        //      that.setData({
        //          listData:pingData
        //      })
        //  }
        this.setData({
            'secondBatchInfo.time': that.queryTime(that.data.secondBatchInfo.secondBatchTime)
        })
        this.setCountDown();
        let secondBatchTimer = setInterval(that.setCountDown, 1000);
        this.setData({
            'secondBatchTimer': secondBatchTimer
        })
    },
    /**
    * 倒计时
    */
    setCountDown: function () {
        let time = 1000;
        // let { listData } = this.data;
        // let list = listData.map((v, i) => {
        //     if (v.time <= 0) {
        //         v.time = 0;
        //     }
        //     let formatTime = this.getFormat(v.time);
        //     v.time -= time;
        //     v.countDown = `${formatTime.hh}:${formatTime.mm}:${formatTime.ss}`;
        //     return v;
        // })
        let secondBatchInfo = this.data.secondBatchInfo;
        if (secondBatchInfo.time <= 0) {
            secondBatchInfo.time = 0;
        }
        let formatTime = this.getFormat(secondBatchInfo.time);
        secondBatchInfo.time -= time;
        secondBatchInfo.countDown = `${formatTime.hh}:${formatTime.mm}:${formatTime.ss}`;
        this.setData({
            'secondBatchInfo': secondBatchInfo
        });
    },
    getFormat(msec) {
        let ss = parseInt(msec / 1000);
        let ms = parseInt(msec % 1000);
        let mm = 0;
        let hh = 0;
        if (ss > 60) {
        mm = parseInt(ss / 60);
        ss = parseInt(ss % 60);
        if (mm > 60) {
        hh = parseInt(mm / 60);
        mm = parseInt(mm % 60);
        }
        }
        ss = ss > 9 ? ss : `0${ss}`;
        mm = mm > 9 ? mm : `0${mm}`;
        hh = hh > 9 ? hh : `0${hh}`;
        return { ss, mm, hh };
    },
    queryTime(pintime){
        var start_date = new Date();
        var end_date = new Date(pintime.replace(/-/g, "/"));
        var days = end_date.getTime() - start_date.getTime();
        console.log("获取到时间差" + days)
        return days;
    },
    handleTimesForRI(time){
        if (time.indexOf('日') != -1 && time.indexOf('月') != -1) {
            return time.substring(0,time.indexOf('月')+1);
        }
        return time;
    },
    BackPage() {
      var that = this;
      wx.navigateBack({
        delta: 1,
        fail: function(){
          that.toHome();
        }
      });
    },
    toHome(){
      wx.reLaunch({
        url: '/pages/home/home',
      })
    },
    doNothing(e){
    },
    switchSeeImage(e){
        let imageIndex = e.currentTarget.dataset.idx;
        let self = this;
        this.setData({
            'imageIndex': imageIndex,
            'seeImages': !self.data.seeImages
        })
    },
    seeImgeChange(e){
        this.setData({
            'imageIndex': e.detail.current
        })
    },
    showModal(e) {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    },
    hideModal(e) {
      this.setData({
        'modalName': null
      })
    },
    changeIcon(e){
        this.setData({
            'subPrice.label': e.currentTarget.dataset.item
        })
    },
    publishInput(e){
        this.setData({
            'subPrice.price': e.detail.value
        })
    },
    useUserAgreement(){
      this.setData({
        userAgreement: !this.data.userAgreement
      })
    },
    useUserAgreement(){
      this.setData({
        userAgreement: !this.data.userAgreement
      })
    },
    onUnload(){
        // 销毁所有的定时器。
        if (this.data.secondBatchTimer) {
            clearInterval(this.data.secondBatchTimer);
        }
    },
    seeOrapply(e){
      let url = e.currentTarget.dataset.url;
      if(url){
        app.globalData.lookReportInfoUrl = url;
        wx.navigateTo({
          url: '/pages/carQueryRecord/detailed/detailed',
        })
      }else{
        this.setData({
          'modalName':'reportApply',
          'applyReportType': e.currentTarget.dataset.type
        })
      }
    },
    goApplyReport(){
      // 申请操作。
      app.sHttp.reportApply({carId:this.data.carInfo.carId,reportType:this.data.applyReportType}).then(res=>{
        this.hideModal();
        app.alert('申请已提交,请等待回复~');
      },err=>{
        app.error(err.msg);
      })
    },
    SeeShipin(){
      if(this.data.secondBatchInfo.videoList.length > 0){
        app.globalData.shipin = this.data.secondBatchInfo.videoList;
        wx.navigateTo({
          url: '/pages/card/secondBatch/shipin/shipin',
        })
      }
    },
    SeeTupian(){
      if(this.data.secondBatchInfo.picList.length > 0){
        app.globalData.tupian = this.data.secondBatchInfo.picList;
        wx.navigateTo({
          url: '/pages/card/secondBatch/tupian/tupian',
        })
      }
    },
    SeeBaogao(){
      if(this.data.secondBatchInfo.reportList.length > 0){
        app.globalData.baogao = this.data.secondBatchInfo.reportList;
        wx.navigateTo({
          url: '/pages/card/secondBatch/baogao/baogao',
        })
      }
    },
})